<template>
  <div style="margin-top: 5px;height: calc(100vh - 35px);background: white;width: calc(100vw - 70px);" >
    <x-form v-if="state.show"
            v-model:api="fApi"
            v-model="formModel"
            :rules="pageOptions.pageRule.rule"
            @mounted="formMounted"
    />
  </div>
</template>

<script setup name="CommonList">
// 列表组件
import {useGlobal} from "@/store/globalStore";
import tool from "@/utils/tool";
import {useRouter, useRoute} from "vue-router";
import {ref, onBeforeMount, getCurrentInstance, nextTick, onActivated, computed} from 'vue'
import bus from "@/store/bus";

const router = useRouter()
const route = useRoute()

const global = useGlobal()
const fApi = ref({})
const instance = getCurrentInstance()
const gridColumns = ref([])
const state = ref({
  show: false,
  showPop: false,
  fApi: {},
  whichPage: route.meta.routeId,
  query: {},
  des: ''
})
const formModel = ref({})
const pageOptions = ref({
  pageRule: {}
})
const formStyle = computed(() => {
  return {
    width: pageOptions.value.width?(pageOptions.value.width+'px'): '100%'
  }
})
const formMounted = (api) =>{
  nextTick(() => {
    api.exec('grid', 'setApi', api)
    setTimeout(() => {
      getList()
      if(typeof pageOptions.value.pageRule.mounted === 'function') {
        pageOptions.value.pageRule.mounted(api)
      }
    }, 100)
  })
}

const getList = () =>{
  if(route.query && !tool.xe.isEmpty(route.query)) {
    let que = route.query
    if(que.search) {
      que = JSON.parse(que.search)
    }
    state.value.query = que
    for(let item in que) {
      if(que[item]) {
        fApi.value.setValue(item, que[item])
      }
    }
    delete que.m
  }
  fApi.value.exec('grid', 'getList')
}

onBeforeMount(async () => {
  pageOptions.value = await tool.getPageRule(state.value.whichPage)
  let ruleArr = []
  if(pageOptions.value.searchRule && typeof pageOptions.value.searchRule === 'object' && pageOptions.value.searchRule.length > 0) {
    for (let i = 0; i < pageOptions.value.searchRule.length; i++) {
      ruleArr.push(pageOptions.value.searchRule[i])
    }
  }
  if(pageOptions.value) {
    let pageRule = pageOptions.value.pageRule
    // if(typeof pageRule.detailGrid !== 'undefined' && !tool.xe.isEmpty(pageRule.detailGrid)) {
    //   detailGridColumns.value = new Function('return ' + pageRule.detailGrid)()
    //   detailGridColumns.value.map(row => {
    //     delete row.filter
    //   })
    // }
    gridColumns.value = pageOptions.value.fields
    if(pageRule) {
      pageOptions.value.pageRule = new Function('_app','_whichPage', '_tool', '_global','_router','_bus','_this', 'return ' + pageRule)(instance.exposed,state.value.whichPage, tool, global, router,bus,pageOptions.value)
      for (let i = 0; i < pageOptions.value.pageRule.rule.length; i++) {
        if(pageOptions.value.pageRule.rule[i].com === 'JGrid') {
          if(typeof pageOptions.value.pageRule.rule[i].check !== 'undefined' && pageOptions.value.pageRule.rule[i].check === true) {
            gridColumns.value.unshift({width: 50,type:'selection',field:'',fixed: 'left'})
          }
          if(typeof pageOptions.value.pageRule.rule[i].seq !== 'undefined' && pageOptions.value.pageRule.rule[i].seq === true) {
            gridColumns.value.unshift({width: 60,type:'index',field:'',fixed: 'left'})
          }
          if(!pageOptions.value.pageRule.rule[i].listUrl) {
            if(pageOptions.value.listUrl)
              pageOptions.value.pageRule.rule[i].listUrl = pageOptions.value.listUrl
          }
          if(!pageOptions.value.pageRule.rule[i].saveUrl) {
            if(pageOptions.value.saveUrl)
              pageOptions.value.pageRule.rule[i].saveUrl = pageOptions.value.saveUrl
          }
          if(!pageOptions.value.pageRule.rule[i].delUrl) {
            if(pageOptions.value.delUrl)
              pageOptions.value.pageRule.rule[i].delUrl = pageOptions.value.delUrl
          }
          if(pageOptions.value.rowBtn) {
            let rowBtn = new Function('_tool','_route','_bus','_app','_router','_whichPage','return '+pageOptions.value.rowBtn)(tool, route,bus,instance.exposed,router,state.value.whichPage)
            rowBtn.visible = true
            gridColumns.value.push(rowBtn)
          }
          if(typeof pageOptions.value.pageRule.rule[i].columns === 'undefined') {
            pageOptions.value.pageRule.rule[i].columns = gridColumns.value
          }
          pageOptions.value.pageRule.rule[i].showFooter = typeof pageOptions.value.pageRule.rule[i].showFooter !== 'undefined' ? pageOptions.value.pageRule.rule[i].showFooter : false
          pageOptions.value.pageRule.rule[i].showPager = typeof pageOptions.value.pageRule.rule[i].showPager !== 'undefined' ? pageOptions.value.pageRule.rule[i].showPager : false

          if (typeof pageOptions.value.pageRule.rule[i].whichPage === 'undefined') {
            pageOptions.value.pageRule.rule[i].whichPage = state.value.whichPage
          }
          pageOptions.value.pageRule.rule[i].columns.map(row => {
            row.width = tool.xe.toNumber(row.width) > 0 ? tool.xe.toNumber(row.width) : 100
          })
        }

        ruleArr.push(pageOptions.value.pageRule.rule[i])
      }

      pageOptions.value.pageRule.rule = ruleArr

      setTimeout(() => {
        state.value.show = true
      }, 100)
    }
  }
})
onActivated(() => {
  if(typeof pageOptions.value.pageRule.activated === 'function') {
    pageOptions.value.pageRule.activated(fApi.value)
  }
})



const sleep = (time) => {
  return new Promise((resolve)=>setTimeout(resolve, time))
}
const verify = (row) => {
  doVerify([row])
}
const verifyBatch = () => {
  let list = fApi.value.exec('grid','getSelect')
  if (list.length === 0) return tool.err('请选择要审核的票据,不超过20张')
  tool.confirm('确定审核 ' + list.length +' 张票据','批量审核').then(() => {
    doVerify(list)
  })
}
const doVerify = async (rows) => {
  tool.loading()
  for (let i = 0; i < rows.length; i++) {
    let data = {
      byScan: 0,
      // menuId: currentMenuId,
      transType: rows[i].transType,
      ids: [rows[i].id],
    }
    if(rows[i].billState !== 'draft') continue
    await tool.post('bill/toAccounted', data).then((ret) => {})
    await sleep(1000)
  }
  tool.hide()
  getList()
}
const waste = (row) => {
  tool.confirm('确定退审？').then(() => {
    doWaste([row])
  })
}
const wasteBatch = () => {
  let list = fApi.value.exec('grid','getSelect')
  if (list.length === 0) return tool.err('请选择要退审核的票据,不超过20张')
  tool.confirm('确定退审核 ' + list.length +' 张票据','批量退审').then(() => {
    doWaste(list)
  })
}
const doWaste = async (rows) => {
  tool.loading()
  for (let i = 0; i < rows.length; i++) {
    let data = {
      ids: [rows[i].id],
      billType: rows[i].billType,
      transType: rows[i].transType,
    }
    if(rows[i].billState !== 'accounted') continue
    await tool.post('bill/toWasted', data).then((ret) => {})
    await sleep(1000)
  }
  tool.hide()
  getList()
}
const del = (row) => {
  let billState = row.billState
  if (billState !== 'draft') return tool.err('不能删除非草稿数据');
  doDel([row])
}
const delBatch = () => {
  let list = fApi.value.exec('grid','getSelect')
  if (list.length === 0) return tool.err('请选择要删除的票据,不超过20张')
  tool.confirm('确定删除 ' + list.length +' 张票据').then(() => {
    doDel(list)
  })
}
const doDel = async (rows) => {
  tool.loading()
  for (let i = 0; i < rows.length; i++) {
    if(rows[i].billState !== 'draft') continue
    let data = {
      ids: [rows[i].id],
      billState: 'del',
      transType: rows[i].transType,
    }
    await tool.post('bill/toDel', data).then((ret) => {})
    await sleep(1000)
  }
  tool.hide()
  getList()
}
const print = (row) => {
  let isCard = route.name === 'card'
  let printList = [{id: row.id}]
  tool.toPrint(printList, true, isCard)
}
const printBatch = () => {
  let list = fApi.value.exec('grid','getSelect')
  if (list.length === 0) return tool.err('请选择要打印的票据,不超过20张')
  tool.confirm('确定打印 ' + list.length +' 张票据').then(() => {
    let printList = []
    let isCard = route.name === 'card'
    for (let i = 0; i < list.length; i++) {
      printList.push({id: list[i].id})
    }
    tool.toPrint(printList, true, isCard)
  })
}

// 页面新增按钮
const pageAdd = () => {
  let whichPage = route.name
  tool.post('page/getEditRule', { whichPage: whichPage }, true).then((ret) => {
    if(ret.stat) {
      let title = ret.data.fileName
      let saveUrl = ret.data.saveUrl
      let width = ret.data.width?ret.data.width:400
      let height = ret.data.height?ret.data.height:300
      let rules = new Function('_tool', 'return ' + ret.data.rule)(tool)
      tool.editor({
        title: '新增 ' + title,
        whichPage,
        width,
        height,
        saveUrl,
        rules,
        btns: [
          {
            name: '保存并继续',
            click: (_api, close) => {
              if (_api.valid()) {
                let formData = _api.getFormData()
                tool.post(formData.saveUrl, {
                  whichPage:  route.name, formData: formData
                }, true).then(ret => {
                  if (ret.stat) {
                    _api.resetFields()
                    getList()
                  }
                })
              }
            }
          },
          {
            name: '保存',
            click: (_api,close) => {
              if (_api.valid()) {
                let formData = _api.getFormData()
                tool.post(formData.saveUrl, {
                  whichPage:  route.name, formData: formData
                }, true).then(ret => {
                  if (ret.stat) {
                    _api.resetFields()
                    close()
                    getList()
                  }
                })
              }
            }
          },
        ]
      })
    }
  })
}
// 行编辑按钮
const pageEdit = (row) => {
  let whichPage = route.name
  tool.post('page/getEditRule', { whichPage: whichPage }, true).then((ret) => {
    if(ret.stat) {
      let title = ret.data.fileName
      let saveUrl = ret.data.saveUrl
      let width = ret.data.width?ret.data.width:400
      let height = ret.data.height?ret.data.height:300
      let rules = new Function('_tool', 'return ' + ret.data.rule)(tool)
      tool.editor({
        title: '编辑 ' + title,
        whichPage,
        width,
        height,
        saveUrl,
        rules,
        model: row,
        btns: [
          {
            name: '保存',
            click: (_api,close) => {
              if (_api.valid()) {
                let formData = _api.getFormData()
                tool.post(formData.saveUrl, {
                  whichPage:  route.name, formData: formData
                }, true).then(ret => {
                  if (ret.stat) {
                    _api.resetFields()
                    close()
                    getList()
                  }
                })
              }
            }
          },
        ]
      })
    }
  })

}
// 行删除按钮
const pageDel = (row) => {
  let whichPage = route.name
  tool.post('page/getEditRule', { whichPage: whichPage }, true).then((ret) => {
    if(ret.stat) {
      let delUrl = ret.data.delUrl?ret.data.delUrl:'page/del'
      tool.confirm('确定删除数据 ？', '删除提示').then(() => {
        tool.post(delUrl,
            {
              whichPage: route.name,
              id: row.id
            }).then(ret => {
          if (ret.stat) {
            getList()
          }
        })
      })
    }
  })
}



defineExpose({getList, verify,waste,del,print,verifyBatch,printBatch,delBatch,wasteBatch, pageAdd,pageEdit,pageDel, })

</script>
<style scoped lang="scss">

.demo-split {
  height: 200px;
  margin-bottom: 20px;
}

.demo-split-pane {
  width: 100%;
  justify-content: center;
  align-items: center;
  display: flex;
  height: 100%;
}
</style>